<template>
    <ul class="list">
        <li class="item" 
        v-for="item of letters" 
        :key="item"
        :ref="item"
        @click="handleLetterClick"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        >{{item}}</li>
    </ul>
</template>
<script>
export default {
    name:'cityAlphabet',
    data () {
        return {
            touchStatus:false,
            startY:0,
            timer:null
        }
    },
    props:{
        cities:Object
    },
    updated(){
        this.startY=this.$refs['A'][0].offsetTop  //获取A距离顶部的高度
    },
    computed:{
        letters () {
        const letters = []
        for (let i in this.cities){
            letters.push(i)
        }
        return letters
        }
    },
    
    methods:{
        handleLetterClick(e){
            this.$emit('change',e.target.innerText)
            //子组件监听父组件里的chenge事件，并传给一个参数
        },
        handleTouchStart(){
            this.touchStatus = true
        },
        handleTouchMove(e){
           if(this.touchStatus){
                if(this.timer){
                    clearTimeout(this.timer)
                }
             this.timer = setTimeout(()=>{            //函数节流：16ms后创建一个timer，timer把move函数走一遍，然后下一个move会清除掉timer并再等16ms走一遍move
              const touchY = e.touches[0].clientY-79   //手指一栋时所在的Y值减去顶部搜索框的高度79
              const index = Math.floor((touchY - this.startY)/20)  //当前手指滑动的位置 index:第几个字母？=（手指所在位置-A所在位置）/每个字母的高度
              if(index >= 0 && index<this.letters.length){       
              this.$emit('change',this.letters[index])
              }
                },16)
           }
        },
        handleTouchEnd(){
            this.touchStatus=false
        }
    }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.list
  position:absolute
  top:1.66rem;
  right:0;
  bottom:0;
  width:0.4rem;
  display flex;
  flex-direction column;
  justify-content :center
  .item
    line-height .4rem;
    text-align center;
    color:$bgColor
</style>
